{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Python介绍\n",
    "\n",
    "> *python你不去认识它，可能没什么，一旦你认识了它，你就会爱上它*\n",
    "\n",
    "Python（英语发音：/ˈpaɪθən/）,\n",
    "是一种面向对象、解释型计算机程序设计语言，由Guido van Rossum于1989年发明，第一个公开发行版发行于1991年。\n",
    "Python是纯粹的自由软件， 源代码和解释器CPython遵循 GPL(GNU General Public License)协议。\n",
    "Python语法简洁清晰，特色之一是强制用空白符(white space)作为语句缩进。\n",
    "Python具有丰富和强大的库。它常被昵称为胶水语言，能够把用其他语言制作的各种模块（尤其是C/C++）很轻松地联结在一起。常见的一种应用情形是，使用Python快速生成程序的原型（有时甚至是程序的最终界面），然后对其中有特别要求的部分，用更合适的语言改写，比如3D游戏中的图形渲染模块，性能要求特别高，就可以用C/C++重写，而后封装为Python可以调用的扩展类库。需要注意的是在您使用扩展类库时可能需要考虑平台问题，某些可能不提供跨平台的实现。\n",
    "## Python开发环境\n",
    "\n",
    "### Python运行环境\n",
    "Python\b基础运行环境只需要到python的官网（[ttps://www.python.org/](https://www.python.org/)）下载相应的\b安装文件即可，安装完成之后需要将python的安装路径添加到系统的path环境变量中。\n",
    "官房的python安装环境只包含有基本的运行环境和基础的软件包，功能比较少。Python强大的地方就在于python可以找到极其多的功能包或模块。\n",
    "要利用Python进行科学计算，就需要一一安装所需的模块，而这些模块可能又依赖于其它的软件包或库，因而安装和使用起来相对麻烦。\n",
    "幸好有人专门在做这一类事情，将科学计算所需要的模块都编译好，然后打包以发行版的形式供用户使用，Anaconda就是其中一个常用的科学计算发行版。\n",
    "下载网址：[https://www.anaconda.com/download/#windows](https://www.anaconda.com/download/#windows)\n",
    "### Python IDE \n",
    "\n",
    "优秀的Python IDE有很多，这里我就介绍几款相对我来说比较常用的！排名不分先后！\n",
    "\n",
    "- pycharm\n",
    "- Atom\n",
    "-\n",
    "VS Code\n",
    "- Sublime Text\n",
    "\n",
    "\n",
    "## Python运行方式\n",
    "\n",
    "### Python\b交互式编程\n",
    "\n",
    "交互式编程不需要创建脚本文件，是通过\n",
    "Python 解释器的交互模式进来编写代码。\n",
    "\n",
    "只需要在命令行中输入 Python 命令即可启动交互式编程\b窗口。\n",
    "\n",
    "在 python\n",
    "提示符中输入以下文本信息，然后按 Enter 键查看运行效果："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(\"Hello, Python!\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Python\b脚本式编程\n",
    "\n",
    "通过脚本参数调用解释器开始执行脚本，直到脚本执行完毕。当脚本执行完成后，解释器不再有效。\n",
    "\n",
    "所有 Python 文件将以\n",
    ".py 为扩展名，例如将上面的print代码放到test.py文件中。\n",
    "\n",
    "假设你已经设置了Python解释器 的 PATH 变量。使用以下命令运行程序：\n",
    "让我们写一个简单的 Python 脚本程序, test.py。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def main():\n",
    "    # print(\"main\")\n",
    "    # print(add(1, 3))\n",
    "    \n",
    "    score = int(input(\"Please input your score : \"))\n",
    "    if 90 <= score <= 100:\n",
    "        print('A')\n",
    "    elif score >= 80:\n",
    "        print('B')\n",
    "    elif score >= 70:\n",
    "        print('C')\n",
    "    elif score >= 60:\n",
    "        print('D')\n",
    "    else:\n",
    "        print('Your score is too low')\n",
    "\n",
    "\n",
    "def add(x, y):\n",
    "    \"\"\"\n",
    "    coment\n",
    "    coment\n",
    "    \"\"\"\n",
    "    hello = \"Hello Hello Hello Hello Hello\\\n",
    "     Hello Hello Hello Hello Hello Hello Hello\\\n",
    "      Hello Hello Hello Hello Hello\"\n",
    "    x = x * 2  # x =2\n",
    "    if y < 0:\n",
    "        y = y * -1\n",
    "        x = x + 1\n",
    "    return x + y\n",
    "\n",
    "def add2(x, y):\n",
    "    return x * 2 + y * 2\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    main()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "attributes": {
     "classes": [
      "dos"
     ],
     "id": ""
    }
   },
   "outputs": [],
   "source": [
    "python test.py"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- 标准的python脚本文件\n",
    " <img src=\"figures/pythonintro.jpg\" width = \"600\" alt=\"python\n",
    "脚本介绍\" align=center />\n",
    "\n",
    "## Python基础语法\n",
    "\n",
    "### 行和缩进\n",
    "-\n",
    "一个程序员学习Python时，遇到的第一个需要注意的地方是，不使用括号来表示代码的类和函数定义块或流程控制。代码块是由行缩进，这是严格执行表示方式。\n",
    "\n",
    "-\n",
    "在缩进位的数目是可变的，但是在块中的所有语句必须缩进相同的量。\n",
    "\n",
    "- python推荐使用4个空格或者tab键作为缩进。\n",
    "\n",
    "\n",
    "### 标识符\n",
    "第一个字符必须是字母表中字母或下划线'_'。\n",
    "标识符的其他的部分有字母、数字和下划线组成。\n",
    "标识符对大小写敏感。\n",
    "\n",
    "\n",
    "### python的保留字"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "['False','None','True','and','as','assert','break','class','continue','def','del','elif','else','except','finally','for','from','global','if','import','in','is','lambda','nonlocal','not','or','pass','raise','return','try','while','with','yield']"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 注释"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "Python中单行注释以#开头，实例如下：\n",
    "#!/usr/bin/python3\n",
    "#第一个注释 \n",
    "print(\"Hello,Python!\")\n",
    "# 第二个注释 执行以上代码，输出结果为：Hello,Python! \n",
    "# 多行注释可以用多个#号：\n",
    "# !/usr/bin/python3\n",
    "# 第一个注释\n",
    "# 第二个注释 \n",
    "print(\"Hello,Python!\")\n",
    "# 执行以上代码，输出结果为：Hello,Python!"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 定义变量：\n",
    "\n",
    "- Python定义变量的方式很简单。\b"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "1"
    }
   },
   "outputs": [],
   "source": [
    "x=1\n",
    "y=2\n",
    "z=x+y"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- Python中的变量不需要声明。每个变量在使用前都必须赋值，变量赋值以后该变量才会被创建\n",
    "\n",
    "- Python\n",
    "3支持int、float、bool、complex（复数）。\n",
    "\n",
    "- 在 Python\n",
    "中，变量就是变量，它没有类型，我们所说的\"类型\"是变量所指的内存中对象的类型。\n",
    "    - 等号（=）用来给变量赋值。\n",
    "    -\n",
    "等号（=）运算符左边是一个变量名,等号（=）运算符右边是存储在变量- 中的值。\n",
    "    - 一个变量可以通过赋值指向不同类型的对象。\n",
    "    -\n",
    "数值的除法（/）总是返回一个浮点数，要获取整数使用//操作符。\n",
    "    - 在混合计算时，Python会把整型转换成为浮点数。\n",
    "\n",
    "代码示例："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "counter = 100      # 整型变量\n",
    "miles = 1000.0       # 浮点型变量\n",
    "name = \"runoob\"     # 字符串\n",
    "print (counter)\n",
    "print (miles)\n",
    "print (name)\n",
    "\n",
    "a = b = c = 1  # 多个变量赋值\n",
    "a, b = 1, 2  # Python可以同时为多个变量赋值"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "其实现在在国外很多大学都是把Python作为计算机语言入门的第一门语言，因为python语言可以说是人类的语言，很容易上手，一眼就能看懂(不过大部分语言都是这样，入门容易深入难，要持之以恒)。\n",
    "### \b字符串\n",
    "- python中的字符串str用单引号(' ')或双引号(\" \")括起来，同时使用反斜杠(\\)转义特殊字符\n",
    "\n",
    "- 字符串可以使用 +\n",
    "运算符串连接在一起，或者用 * 运算符重复\n",
    "\n",
    "- 使用三引号('''...'''或\"\"\"...\"\"\")可以指定一个多行字符串\n",
    "\n",
    "-\n",
    "如果不想让反斜杠发生转义，可以在字符串前面添加一个 r 或 R, 表示原始字符串。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "text = 'ice'+' cream'\n",
    "print(text)\n",
    "\n",
    "text = 'ice cream '*3\n",
    "print(text)\n",
    "\n",
    "text = '''呵呵\n",
    "          呵呵呵\n",
    "          呵呵呵呵'''\n",
    "\n",
    "print(text)\n",
    "text = 'ice\\\n",
    "        cream'\n",
    "print(text)\n",
    "\n",
    "print(r\"this is a line with \\n\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- 字符串有两种索引方式，第一种是从左往右，从0开始依次增加；第二种是从右往左，从-1开始依次减少。\n",
    "\n",
    "-\n",
    "python中没有单独的字符类型，一个字符就是长度为1的字符串"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "text = 'ice cream'\n",
    "print(len(text))\n",
    "\n",
    "print(text[0])  # i\n",
    "print(text[-9])  # i\n",
    "\n",
    "print(text[8])  # m\n",
    "print(text[-1])  # m"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- python字符串不能被改变。向一个索引位置赋值会导致错误"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "text = 'ice cream'\n",
    "text[0] = 't'  # 报错\n",
    "print(text) "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- 还可以对字符串进行切片，获取一段子串。用冒号分隔两个索引，形式为变量[头下标:尾下标]。\n",
    "- 截取的范围是前闭后开的，并且两个索引都可以省略\n",
    "\n",
    "### 分支\n",
    "- if-else 语句与其他语言类似，不再赘述\n",
    "\n",
    "- if-elif-else 语句，相当于c或java语言中的if-else if-else"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "while True:\n",
    "    score = int(input(\"Please input your score : \"))\n",
    "    if 90 <= score <= 100:\n",
    "        print('A')\n",
    "    elif score >= 80:\n",
    "        print('B')\n",
    "    elif score >= 70:\n",
    "        print('C')\n",
    "    elif score >= 60:\n",
    "        print('D')\n",
    "    else:\n",
    "        print('Your score is too low')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 循环\n",
    "\n",
    "while循环语句一般形式："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "while 判断条件：\n",
    "    statement"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import random\n",
    "\n",
    "print(\"hello world!\\n\")\n",
    "number = random.randint(1, 10)\n",
    "temp = input(\"Please input a number : \")\n",
    "i = int(temp)\n",
    "\n",
    "while i != number:\n",
    "    print(\"wrong...\")\n",
    "    if i < number:\n",
    "        print(\"required a bigger number\")\n",
    "    else:\n",
    "        print(\"required a smaller number\")\n",
    "    temp = input(\"Please input a number : \")\n",
    "    i = int(temp)\n",
    "\n",
    "print(\"yes...\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "for循环的一般格式如下："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for <variable> in <sequence>:\n",
    "　　<statements>\n",
    "else:\n",
    "　　<statements>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "languaegs = ['C','c++','java','python']\n",
    "for language in languaegs:\n",
    "    print(language, len(language))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> 循环语句可以有else子句\n",
    "它在穷尽列表(以for循环)或条件变为假(以while循环)循环终止时被执行\n",
    "但循环被break终止时不执行.\n",
    "如下查寻质数的循环例子:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for num in range(2, 10):\n",
    "    for x in range(2, num):\n",
    "        if num%x == 0:\n",
    "            print(num, 'equals', x, '*', num//x)\n",
    "            break\n",
    "    else:\n",
    "        # 循环中没有找到元素\n",
    "        print(num, 'is a prime number')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> 如果需要遍历数字序列，可以使用内置range()函数："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# range()函数,含头不含尾\n",
    "# 0~4\n",
    "for i in range(5):\n",
    "    print(i)\n",
    "\n",
    "# 2~7\n",
    "for i in range(2, 8):\n",
    "    print(i)\n",
    "\n",
    "# 1~9 步长为3\n",
    "for i in range(1, 10, 3):\n",
    "    print(i)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 数据结构\n",
    "\n",
    "python中数有四种类型：列表、元组、字典、set。\n",
    "\n",
    "- list:\n",
    "Python内置的一种数据类型是列表。lists是一个有序的集合，可以添加与删除元素。\n",
    "    > 生成它是用  []  就可以啦；"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "    > 调用它时，用下标调用就可以啦（从0开始）；如第一个元素，list[0];倒数第一个，list[-1];\n",
    "\n",
    "    >\n",
    "可以用len()函数获得list元素的个数；\n",
    "\n",
    "    > 在尾部添加用append(),\n",
    "中间插入用insert()；尾部删除用pop()；指定位置删除为pop(i）；\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- 元组（tuple):tuple和list非常类似，但是tuple一旦初始化就不能修改。只要记住它不能修改就可以啦。很安全。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "    > 用 （） 定义啊。\n",
    "\n",
    "    > 用下标调用,即tuple[1]；\n",
    "\n",
    "    > 注意：它定义一个元素的tuple时，一定要这样写，如：name\n",
    "= (‘yin’,)， 千万别写成 name = (‘yin’);\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- 字典（dictionary)：它就是 键－值\n",
    "对。类似在C++语言中为map的容器。它的特点就是可以快速查找，但需要占用大量的内存，内存浪费多。通过key计算位置的算法称为哈希算法（Hash）。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "    > 用 {} 定义dictionary哦；\n",
    "\n",
    "    > 随着dictionary的增加，查找时间不会增加的。\n",
    "\n",
    "    >\n",
    "多次对一个key放入value，后面的值会把前面的值冲掉：\n",
    "\n",
    "    > 可以用  ‘key’in dic 或\n",
    "dic.get(‘key’)的方法来查看key是否存在。注意：dict提供的get方法，如果key不存在，可以返回None，或者自己指定的value，返回None的时候Python的交互式命令行不显示结果。\n",
    "> 删除用: pop(key)。添加时，直接用key值的索引添加就可以的。\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "-\n",
    "集合(set):set和dict类似，也是一组key的集合，但不存储value。由于key不能重复，所以，在set中，没有重复的key。set和dict的唯一区别仅在于没有存储对应的value，但是，set的原理和dict一样，所以，同样不可以放入可变对象。\n",
    "> 要创建一个set，需要提供一个list作为输入集合：\n",
    "\n",
    "> 通过add(key)与remove(key)添加与删除元素；\n",
    "\n",
    "\n",
    "## Python科学计算\n",
    "Python专用的科学计算扩展库有很多，例如三个十分经典的科学计算扩展库：NumPy、SciPy和matplotlib，它们分别为Python提供了快速数组处理、数值运算以及绘图等功能。因此Python语言十分适合工程技术、科研人员处理实验数据，制作图表，甚至开发科学计算应用程序。\n",
    "### numpy\n",
    " NumPy(Numerical Python) 是 Python\n",
    "语言的一个扩展程序库，支持大量的维度数组与矩阵运算，此外也针对数组运算提供大量的数学函数库。\n",
    "\n",
    "NumPy 的前身 Numeric 最早是由 Jim\n",
    "Hugunin 与其它协作者共同开发，2005 年，Travis Oliphant 在 Numeric 中结合了另一个同性质的程序库 Numarray\n",
    "的特色，并加入了其它扩展而开发了 NumPy。NumPy 为开放源代码并且由许多协作者共同维护开发。\n",
    "\n",
    "NumPy\n",
    "是一个运行速度非常快的数学库，主要用于数组计算，包含：\n",
    "\n",
    "- 一个强大的N维数组对象 ndarray\n",
    "- 广播功能函数\n",
    "- 整合 C/C++/Fortran\n",
    "代码的工具\n",
    "- 线性代数、傅里叶变换、随机数生成等功能\n",
    "\n",
    "NumPy 通常与 SciPy（Scientific Python）和\n",
    "Matplotlib（绘图库）一起使用， 这种组合广泛用于替代 MatLab，是一个强大的科学计算环境，有助于我们通过 Python 学习数据科学或者机器学习。\n",
    "[Numpy官网](https://numpy.org)\n",
    "\n",
    "![numpy](figures/numpy.png)\n",
    "\n",
    "#### Numpy examples"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 导入numpy的几种方法\n",
    "import numpy\n",
    "import numpy as np\n",
    "from numpy import *\n",
    "from numpy import array, sin"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- scipy\n",
    "![scipy](figures/scipy.png)\n",
    "\n",
    "### Scipy examples\n",
    "\n",
    "- matplotlib\n",
    "![numpy](figures/matplotlib.png)\n",
    "\n",
    "### matplotlib example"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
